<?php
use library\core\config;

function error($message='')
{
    return config::get("error") ? exit(json(array($message))) : errorpage();
}

function json($arr){
    $json = new Services_JSON();
    return $json->encode($arr);
}

function errorpage(){//错误转向
    header('HTTP/1.1 404 Not Found');
    include template('errorpage');
}

function getip()
{
    if(getenv("HTTP_CLIENT_IP")&&strcasecmp(getenv("HTTP_CLIENT_IP"),"unknown")){
        $ip = getenv("HTTP_CLIENT_IP");
    }elseif(getenv("HTTP_X_FORWARDED_FOR")&&strcasecmp(getenv("HTTP_X_FORWARDED_FOR"),"unknown")){
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    }elseif(getenv("REMOTE_ADDR")&&strcasecmp(getenv("REMOTE_ADDR"),"unknown")){
        $ip = getenv("REMOTE_ADDR");
    }elseif(isset($_SERVER['REMOTE_ADDR'])&&$_SERVER['REMOTE_ADDR']&&strcasecmp($_SERVER['REMOTE_ADDR'],"unknown")){
        $ip = $_SERVER['REMOTE_ADDR'];
    }else{
        $ip = "unknown";
    }
    return ($ip);
}


/**
 *@todo: 判断是否为post
 */
if(!function_exists('is_post')){
    function is_post()
    {
        return isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD'])=='POST';
    }
}

/**
 *@todo: 判断是否为get
 */
if(!function_exists('is_get')){
    function is_get()
    {
        return isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD'])=='GET';
    }
}

/**
 *@todo: 判断是否为ajax
 */
if(!function_exists('is_ajax')){
    function is_ajax()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtoupper($_SERVER['HTTP_X_REQUESTED_WITH'])=='XMLHTTPREQUEST';
    }
}

/**
 *@todo: 判断是否为命令行模式
 */
if(!function_exists('is_cli')){
    function is_cli()
    {
        return (PHP_SAPI === 'cli' OR defined('STDIN'));
    }
}

function include_file($dir_path = null) {
    $root_path = realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
    if (is_array($dir_path)) {
        foreach ($dir_path as $path) {
            if (is_file($root_path.$path)) {
                include_once str_replace('\\', '/', $root_path.$path);
            }
        }
    } else {
        $file = $root_path.$dir_path;
        if (is_file($file)) {
            include_once str_replace('\\', '/', $file);
        }
    }
}

function success($data = null)
{
    include_file('include/Response.php');
    Response::success($data);
}

function fail($data = null)
{
    include_file('include/Response.php');
    Response::fail($data);
}

function guidv4()
{
    if (function_exists('com_create_guid') === true)
        return trim(com_create_guid(), '{}');

    $data = openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s%s%s%s%s%s%s', str_split(bin2hex($data), 4));
}

function generate_serial($serial_no='') {
    $time = date('y-m-d-H-i-s');
    $atime = explode('-', $time);
    foreach ($atime as $stime) {
        $itime = $stime * 1;
        if ($itime < 26) {
            // 65(A)-90(Z)
            $serial_no.=chr(65 + $itime);
            continue;
        }
        // 48(0)-57(9)
        if ($itime >= 48 && $itime <= 57) {
            $serial_no.=chr($stime);
            continue;
        }
        $serial_no.=$stime;
    }
    return $serial_no;
}

function createDirectory($path, $mode = 0775, $recursive = true)
{
    if (is_dir($path)) {
        return true;
    }
    $parentDir = dirname($path);
    if ($recursive && !is_dir($parentDir)) {
        createDirectory($parentDir, $mode, true);
    }
    try {
        $result = mkdir($path, $mode);
        chmod($path, $mode);
    } catch (\Exception $e) {
        throw new \Exception("Failed to create directory '$path': " . $e->getMessage(), $e->getCode(), $e);
    }

    return $result;
}

/**
 * 实现多种字符解码方式
 * @param $input 需要解码的字符串
 * @param $_output_charset 输出的解码格式
 * @param $_input_charset 输入的解码格式
 * @return 解码后的字符串
 */
function charsetDecode($input,$_input_charset ,$_output_charset) {
    $output = "";
    if(!isset($_input_charset) )$_input_charset  = $_input_charset ;
    if($_input_charset == $_output_charset || $input ==null ) {
        $output = $input;
    } elseif (function_exists("mb_convert_encoding")) {
        $output = mb_convert_encoding($input,$_output_charset,$_input_charset);
    } elseif(function_exists("iconv")) {
        $output = iconv($_input_charset,$_output_charset,$input);
    } else die("sorry, you have no libs support for charset changes.");
    return $output;
}

/**
 * 保存文本数据日志（适用所有的日志记录，保存在根目录下的log目录中，并且按天记录日志）
 * @param $data 记录数据
 * @param string $filename 日志名称（默认为app_日期.log，文件名前可加n级目录，以‘/’分隔）
 * @param string $requestSource 请求来源（默认为记录客户端IP和请求方法）
 * @param string $category 错误类型（自定义，默认为normal正常级别）
 * @param bool $log 是否记录日志（默认调用即记录）
 */
function logger($data = null, $filename = '', $requestSource = '',  $category = 'normal', $log = true )
{
    if( !$log ) return;

    $dir  = './logs/';
    $last = '';

    if( strrpos($filename, '/') ){
        $filename_explode = explode('/', $filename);
        $last = end($filename_explode);
        unset($filename_explode[count($filename_explode)-1]);
        $dir = $dir.implode('/', $filename_explode).'/';
    }

    if( !file_exists($dir) ){
        createDirectory($dir);
    }

    if( empty($filename) ){
        $filename = $_SERVER['REQUEST_METHOD'];
    }

    if( !$requestSource && isset($_SERVER['REQUEST_METHOD']) ){
        $requestSource = 'IP:' . getip() . '|' . 'REQUEST_METHOD:' . $_SERVER['REQUEST_METHOD'];
    }

    $path = strrpos($filename, '/') ? $dir.$last : "{$dir}/{$filename}";
    $file = $path.'_'.date("Ymd",time()).'.txt';

    charsetDecode($file, 'gbk', 'utf8');

    try{
        $temp = @file_get_contents($file);
    }catch(\Exception $e){
        $temp = '';
    }

    $string  = date('Y-m-d H:i:s',time());
    $string .= "[$requestSource]";
    $string .= "[$category]:".PHP_EOL;
    $string .= print_r($data, true).PHP_EOL;

    $content = $string.$temp;
    charsetDecode($content, 'gbk', 'utf8');
    @file_put_contents($file, $content );
    !1 && @file_put_contents($file, $string, FILE_APPEND | LOCK_EX );
}


/**
 * 获取模块配置文件内容
 *
 * @param null $file_name 文件地址 （精确到根目录下，如'config/config.php'）
 * @return array|mixed 返回配置文件内容
 */
function include_config($file_name = null, $keys = '') {
    $ds = DIRECTORY_SEPARATOR;
    $root_path = realpath(dirname(__DIR__)) . $ds;

    if (!empty($keys)) {
        $keys = explode('.', $keys);
    }

    $include_arr = [];
    if (is_array($file_name)) {
        foreach ($file_name as $path) {
            $include_arr = array_merge($include_arr, [include str_replace('\\', '/', $root_path . $path)]);
        }
    } else {
        $include_arr = include str_replace('\\', '/', $root_path . $file_name);
    }

    $cfg = $include_arr;
    if ($include_arr && !empty($keys)) {
        foreach ($keys as $i => $key) {
            $cfg = $cfg[$key];
        }
    }

    while (list($key, $value) = each($cfg)) {
        if (is_array($value)) {
            $cfg[$key] = trimArray($value);
        } else {
            $cfg[$key] = is_bool($value) ? $value : trim($value);
        }
    }

    return $cfg ? $cfg : null;

    return $include_arr;
}


function objectToArray($object){
    if(!is_object($object) && !is_array($object)){
        return $object;
    }
    if(is_object($object)){
        $object = get_object_vars( $object );
    }
    return array_map( 'objectToArray', $object );
}


/**
 * @param        $url
 * @param string $method
 * @param null   $postdata
 * @param int    $timeout
 *
 * @return resource|false
 */
function curl_send($url, $method = 'get', $postdata = null, $timeout = 30)
{
    if ($method == 'get') {
        $url .= '?' . http_build_query($postdata);
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    if ($method == 'post') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata));
    }

    $response   = curl_exec($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    return $response;
}